<template>
  <!--  地图容器 -->
  <div id="map" style="height: 100vh; width: 100%">

  </div>
  <div class="calculation-box">
    <p>点击地图规选</p>
    <div id="calculate-area">
      {{state.drawArea}}平方公里
    </div>
  </div>


</template>
<script setup>
import mapboxgl  from "mapbox-gl";
import MapboxDraw from '@mapbox/mapbox-gl-draw'
import MapboxLanguage from '@mapbox/mapbox-gl-language'; //可以将标签改为中文
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'
import {onMounted, reactive} from "vue";

//引入turf.js
import * as turf from '@turf/turf'
let map;
let draw;
/*
* 【使用GeoJSON source将多边形添加到地图】
* 地图通过addSource添加GeoJSON数据，之后通过addLayer创建新的填充图层并应用paint属性来设置多边形外观的样式
*
* */

const state = reactive({
  drawArea: 0
})
onMounted(() => {
  mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94ZGV2dXNlcjUyMCIsImEiOiJjbHFrb2w3M2IyNHB2MnFtZWx1ZzFjNHZmIn0.CMoLsalSeXlJiLBNyUK1nA'
  // init map
  map = new mapboxgl.Map({
    container: 'map', // 地图容器id,
    style: 'mapbox://styles/mapbox/streets-v12', // 地图样式
    center: [-77.04, 38.907], // 地图初始中心【经纬度】 starting position
    zoom: 11.15, // 地图初始缩放界别41 // starting zoom
    projection: 'globe', // 地图投影 为3D地球
    pitch: 62, // 相对于地面3D视角的角度 // starting pitch
    bearing: -20, // 东西南北 方向 正北方为0 // starting bearing
    antialias: false, // 抗锯齿，通过false关闭提升性能
    essential: true,
    renderWorldCopies: false, //可理解为loop，在projection: 'globe'时无效
    skipOnboarding: true,//可选择不等待瓦片加载
  })

  // Mapbox GL JS中的图层是异步的，通过使用事件绑定在合适的时间更改地图
  // POI 信息点
  //
  map.on('style.load', () => {
    initControls();
    initSourceAndLayers();
  })

})

const initSourceAndLayers = () => {
  map.addSource('places', {
// This GeoJSON contains features that include an "icon"
// property. The value of the "icon" property corresponds
// to an image in the Mapbox Streets style's sprite.
    'type': 'geojson',
    'data': {
      'type': 'FeatureCollection',
      'features': [
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Make it Mount Pleasant</strong><p><a href="http://www.mtpleasantdc.com/makeitmtpleasant" target="_blank" title="Opens in a new window">Make it Mount Pleasant</a> is a handmade and vintage market and afternoon of live entertainment and kids activities. 12:00-6:00 p.m.</p>',
            'icon': 'theatre'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.038659, 38.931567]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Mad Men Season Five Finale Watch Party</strong><p>Head to Lounge 201 (201 Massachusetts Avenue NE) Sunday for a <a href="http://madmens5finale.eventbrite.com/" target="_blank" title="Opens in a new window">Mad Men Season Five Finale Watch Party</a>, complete with 60s costume contest, Mad Men trivia, and retro food and drink. 8:00-11:00 p.m. $10 general admission, $20 admission and two hour open bar.</p>',
            'icon': 'theatre'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.003168, 38.894651]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Big Backyard Beach Bash and Wine Fest</strong><p>EatBar (2761 Washington Boulevard Arlington VA) is throwing a <a href="http://tallulaeatbar.ticketleap.com/2012beachblanket/" target="_blank" title="Opens in a new window">Big Backyard Beach Bash and Wine Fest</a> on Saturday, serving up conch fritters, fish tacos and crab sliders, and Red Apron hot dogs. 12:00-3:00 p.m. $25.grill hot dogs.</p>',
            'icon': 'bar'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.090372, 38.881189]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Ballston Arts & Crafts Market</strong><p>The <a href="http://ballstonarts-craftsmarket.blogspot.com/" target="_blank" title="Opens in a new window">Ballston Arts & Crafts Market</a> sets up shop next to the Ballston metro this Saturday for the first of five dates this summer. Nearly 35 artists and crafters will be on hand selling their wares. 10:00-4:00 p.m.</p>',
            'icon': 'art-gallery'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.111561, 38.882342]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Seersucker Bike Ride and Social</strong><p>Feeling dandy? Get fancy, grab your bike, and take part in this year\'s <a href="http://dandiesandquaintrelles.com/2012/04/the-seersucker-social-is-set-for-june-9th-save-the-date-and-start-planning-your-look/" target="_blank" title="Opens in a new window">Seersucker Social</a> bike ride from Dandies and Quaintrelles. After the ride enjoy a lawn party at Hillwood with jazz, cocktails, paper hat-making, and more. 11:00-7:00 p.m.</p>',
            'icon': 'bicycle'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.052477, 38.943951]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Capital Pride Parade</strong><p>The annual <a href="http://www.capitalpride.org/parade" target="_blank" title="Opens in a new window">Capital Pride Parade</a> makes its way through Dupont this Saturday. 4:30 p.m. Free.</p>',
            'icon': 'rocket'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.043444, 38.909664]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Muhsinah</strong><p>Jazz-influenced hip hop artist <a href="http://www.muhsinah.com" target="_blank" title="Opens in a new window">Muhsinah</a> plays the <a href="http://www.blackcatdc.com">Black Cat</a> (1811 14th Street NW) tonight with <a href="http://www.exitclov.com" target="_blank" title="Opens in a new window">Exit Clov</a> and <a href="http://godsilla.bandcamp.com" target="_blank" title="Opens in a new window">Gods’illa</a>. 9:00 p.m. $12.</p>',
            'icon': 'music'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.031706, 38.914581]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>A Little Night Music</strong><p>The Arlington Players\' production of Stephen Sondheim\'s  <a href="http://www.thearlingtonplayers.org/drupal-6.20/node/4661/show" target="_blank" title="Opens in a new window"><em>A Little Night Music</em></a> comes to the Kogod Cradle at The Mead Center for American Theater (1101 6th Street SW) this weekend and next. 8:00 p.m.</p>',
            'icon': 'music'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.020945, 38.878241]
          }
        },
        {
          'type': 'Feature',
          'properties': {
            'description':
              '<strong>Truckeroo</strong><p><a href="http://www.truckeroodc.com/www/" target="_blank">Truckeroo</a> brings dozens of food trucks, live music, and games to half and M Street SE (across from Navy Yard Metro Station) today from 11:00 a.m. to 11:00 p.m.</p>',
            'icon': 'music'
          },
          'geometry': {
            'type': 'Point',
            'coordinates': [-77.007481, 38.876516]
          }
        }
      ]
    }
  });

  // Add a layer showing the places
  map.addLayer({
    'id': 'places',
    'type': 'symbol',
    'source': 'places',
    'layout': {
      'icon-image': ['get', 'icon'],
      'icon-allow-overlap': true
    }
  })

  /*
  * When a click event occurs on a feature in the places layer,
  * open a popup at the location of the feature, with description
  * HTML from its properties.
  * */
  map.on('click', 'places', (e) => {
    console.log('output-> 点击事件', e)
    // Copy coordinates array.
    const coordinates = e.features[0].geometry.coordinates.slice();
    const description = e.features[0].properties.description

    // Ensure that if the map is zoomed
    // out such that multiple copies of the feature
    // are visible, the popup appears
    // over the copy being pointed to.
    while(Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
      coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }

    // 绘制弹窗
    // 设置所在经纬度和弹窗HTML并加载到地图
    new mapboxgl.Popup()
      .setLngLat(coordinates)
      .setHTML(description)
      .addTo(map);
  })

  // Change the cursor to a point
  // when the mouse is over the places layer.
  map.on('mouseenter', 'places', () => {
    map.getCanvas().style.cursor = 'pointer'
  })

  // Change it back to a pointer when it leaves.
  map.on('mouseleave', 'places', () => {
    map.getCanvas().style.cursor = ''
  })

}
const initControls = () => {
  map.addControl(new MapboxLanguage({ defaultLanguage: 'zh-Hans' }));
  map.addControl(new mapboxgl.GeolocateControl())
  map.addControl(new mapboxgl.FullscreenControl())
  map.addControl(new mapboxgl.NavigationControl({visualizePitch: true}))
  map.addControl(new mapboxgl.ScaleControl())
}

</script>


<style scoped lang="scss">
.mapboxgl-popup {
  max-width: 400px;
  font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
}
</style>
